/*************************************************
	Validator v1.05
	code by 我佛山人
	wfsr@msn.com
	--------------
	Validator v1.05.5
	update by:xwk
	2008-05-31
	soft@PoP4u.NeT
	QQ:56433593
	------------------------------------------------
	v1.05.5 12:20 2008-06-06
	- Ajax验证
	+ 日期比较 CompareDate
	* 修正 Compare to为栏位id,修正为数字比较
	+ Compare 组合验证 <to>ccc+,aaa+bbb</to> 表示ccc栏位的值+该栏位值 和 aaa 栏位的值+bbb栏位的值比较
	  <to>+ccc,aaa+bbb</to> 表示该栏位值+ccc栏位的值 和 aaa 栏位的值+bbb栏位的值比较
	+ Compare numberMode 属性,为true 表示为数字模式 否则为字符串拼接模式
	+ 所有getElementById() 统一用 this.$() 集中处理
	+ DataType 添加 Script 类型 <script>属性,自定义JavaScript

	v1.05.4 18:40 2008-06-04
	+ Ajax验证

	v1.05.3 17:01 2008-6-3
	+ 当错误标题为空时不显示
	+ 设置出错控件的背景颜色 this.ErrorColor

	v1.05.2 00:37 2008-6-3
	+ 添加组合验证
	+ 添加5个正则表达式验证

	v1.05.1
	+ 添加第9个模式,将错误信息打印到一个层中		
	+ 添加使用xml文件动态绑定表单属性
	------------------------------------------------
	实例:onsubmit = return Validator.Validate(this,9,'Error Message','errorSpan')
	参数:form对象,9(第9种模式),错误信息的标题,错误层的id
		
    实例:onload="bindingValidatorForm('addForm','validation.xml')"
    参数:form名字,xml文件路径
    配置文件示例:
    <?xml version="1.0" encoding="utf-8"?>
    <formset>
        <form name="addForm">
            <field id="name">
                <dataType>Require,Limit</dataType>
                <msg_Require>用户名为空</msg_Require>
                <msg_Limit>用户名必须大于4位小于10位</msg_Limit>
                <min>4</min>
                <max>10</max>
            </field>
            <field id="pwd">
                <dataType>Require</dataType>
                <msg>密码不能为空</msg>
            </field>
        </form>
    </formset>
*************************************************/
 Validator = {
	Require : /.+/,
	Email : /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
	Phone : /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/,
	Mobile : /^((\(\d{2,3}\))|(\d{3}\-))?13\d{9}$/,
	Url : /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,
	IdCard : "this.IsIdCard(value)",
	Currency : /^\d+(\.\d+)?$/,
	Number : /^\d+$/,
	Zip : /^[1-9]\d{5}$/,
	QQ : /^[1-9]\d{4,8}$/,
	Integer : /^[-\+]?\d+$/,
	Double : /^[-\+]?\d+(\.\d+)?$/,
	English : /^[A-Za-z]+$/,
	Chinese :  /^[\u0391-\uFFE5]+$/,
	Username : /^[a-z]\w{3,}$/i,
	UnSafe : /^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/,
	IsSafe : function(str){return !this.UnSafe.test(str);},
	SafeString : "this.IsSafe(value)",
	Filter : "this.DoFilter(value, getAttribute('accept'))",
	Limit : "this.limit(value.length,getAttribute('min'),  getAttribute('max'))",
	LimitB : "this.limit(this.LenB(value), getAttribute('min'), getAttribute('max'))",
	Date : "this.IsDate(value, getAttribute('min'), getAttribute('format'))",
	Repeat : "value == this.$(getAttribute('to')).value",
	Range : "getAttribute('min') < (value|0) && (value|0) < getAttribute('max')",
	Compare : "this.compare(value,getAttribute('operator'),getAttribute('to'),getAttribute('numberMode'))",
	CompareDate : "this.compareDate(value,getAttribute('operator'),this.$(getAttribute('to')).value)",
	Custom  : "this.Exec(value, getAttribute('regexp'))",
	Custom2 : "this.Exec(value, getAttribute('regexp2'))",
	Custom3 : "this.Exec(value, getAttribute('regexp3'))",
	Custom4 : "this.Exec(value, getAttribute('regexp4'))",
	Custom5 : "this.Exec(value, getAttribute('regexp5'))",
	Group : "this.MustChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'))",
	Script : "eval(getAttribute('script'));",
	ErrorItem : [document.forms[0]],
	ErrorMessage : ["以下原因导致提交失败：\t\t\t\t"],
	ErrorColor : "#FFE4C4",
	Validate : function(theForm, mode,errorTitle,errorSpan){
		if(typeof theForm == "string"){
			theForm = this.$(theForm) || document.forms[theForm];
		}
		var obj = theForm || event.srcElement;
		var count = obj.elements.length;
		this.ErrorMessage.length = 1;
		this.ErrorItem.length = 1;
		this.ErrorMessage[0] = errorTitle;
		/*
		if (errorTitle != ''){
			this.ErrorMessage[0] = errorTitle;
		}else{
			this.ErrorMessage.splice(0,1);
		}*/
		this.ErrorItem[0] = obj;
		if (mode == 9){
			this.ClearErrorSpan(errorSpan);
		}
		for(var i=0;i<count;i++){
			with(obj.elements[i]){
				var _dataType = getAttribute("dataType");
				//if(typeof(_dataType) == "object" || typeof(this[_dataType]) == "undefined")  continue;				
				if(!_dataType)  continue;
				this.ClearState(obj.elements[i]);
				if(getAttribute("require") == "false" && value == "") continue;
				var _dataTypes = _dataType.split(',');
				for (var j=0; j<_dataTypes.length; j++){
					switch(_dataTypes[j]){
						case "IdCard" :
						case "Date" :
						case "Repeat" :
						case "Range" :
						case "Compare" :
						case "CompareDate":
						case "Custom" :
						case "Custom2" :
						case "Custom3" :
						case "Custom4" :
						case "Custom5" :
						case "Group" : 
						case "Limit" :
						case "LimitB" :
						case "SafeString" :
						case "Filter" :
						case "Script" :
							if(!eval(this[_dataTypes[j]])){
								if (getAttribute("msg_"+_dataTypes[j])){
									this.AddError(i, getAttribute("msg_"+_dataTypes[j]));
								}else{
									this.AddError(i, getAttribute("msg"));
								}
								j = _dataTypes.length;
							}
							break;
						default :
							if(!this[_dataTypes[j]].test(value)){
								if (getAttribute("msg_"+_dataTypes[j])){
									this.AddError(i, getAttribute("msg_"+_dataTypes[j]));
								}else{
									this.AddError(i, getAttribute("msg"));
								}
								j = _dataTypes.length;
							}
							break;
					}
				}
			}
		}
		if(this.ErrorMessage.length > 1){
			if (this.ErrorMessage[0] == ''){
				this.ErrorMessage.splice(0,1);
			}
			mode = mode || 1;
			var errCount = this.ErrorItem.length;
			switch(mode){
			case 2 :
				for(var i=1;i<errCount;i++)
					this.ErrorItem[i].style.color = "red";
			case 1 :
				alert(this.ErrorMessage.join('\n'));
				this.ErrorItem[1].focus();
				break;
			case 3 :
				for(var i=1;i<errCount;i++){
				try{
					var span = document.createElement("SPAN");
					span.id = "__ErrorMessagePanel";
					span.style.color = "red";
					this.ErrorItem[i].parentNode.appendChild(span);
					span.innerHTML = this.ErrorMessage[i].replace(/\d+:/,"*");
					}
					catch(e){alert(e.description);}
				}
				this.ErrorItem[1].focus();
				break;
			case 9 : //add by:xwk
				var errorSpanElement = this.$(errorSpan);
				if (errorSpanElement){
					errorSpanElement.style.display='';
					errorSpanElement.innerHTML = this.ErrorMessage.join('<br/>');
					this.ErrorItem[1].focus();
				}else{
					alert('模式为9时,需要一个显示层');
				}
				break;
			default :
				alert(this.ErrorMessage.join("\n"));
				break;
			}
			return false;
		}
		return true;
	},
	limit : function(len,min, max){
		min = min || 0;
		max = max || Number.MAX_VALUE;
		return min <= len && len <= max;
	},
	LenB : function(str){
		return str.replace(/[^\x00-\xff]/g,"**").length;
	},
	ClearState : function(elem){
		with(elem){
			if(style.color == "red")
				style.color = "";
			var lastNode = parentNode.childNodes[parentNode.childNodes.length-1];
			if(lastNode.id == "__ErrorMessagePanel")
				parentNode.removeChild(lastNode);
			var oldStyle = getAttribute('oldStyle');
			style.backgroundColor = oldStyle;
		}		
	},
	ClearErrorSpan : function (errorSpan){
		this.$(errorSpan).style.display = 'none';
	},
	AddError : function(index, str){
		this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index];
		this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length + ":" + str;
		this.ErrorItem[this.ErrorItem.length -1 ].style.backgroundColor= this.ErrorColor;
	},
	Exec : function(op, reg){
		return new RegExp(reg,"g").test(op);
	},
	compare : function(op1,operator,op2,numberMode){
		var op2s;
		var op2adds;
		var num1='';
		var num2='';
		if (numberMode){
			num1 = 0;
			num2 = 0;
		}		
		if (op2.indexOf(',')>-1){
			op2s = op2.split(',');
			if (op2s.length != 2){
				alert('[Validator.js] compare 只支持2个进行比较,连接符用+');
				return false;
			}
			op2adds = op2s[0].split('+');
			for (var i = 0 ; i<op2adds.length ; i++){
				if (i == 0 & op2adds[0] == ''){
					num1 = Number(op1);
				}else if (i == op2adds.length-1 && op2adds[op2adds.length-1] == ''){
					num1 += Number(op1);
				}else{
					num1 += Number(this.$(op2adds[i]).value);
				}
			}
			op2adds = op2s[1].split('+');
			for (var i=0;i<op2adds.length ;i++ ){
				num2 += Number(this.$(op2adds[i]).value);
			}
		}else{
			num1 = op1;
			num2 = this.$(op2).value;
		}
		num1 = Number(num1);
		num2 = Number(num2);
		switch (operator) {
			case "NotEqual":
				return (num1 != num2);
			case "GreaterThan":
				return (num1 > num2);
			case "GreaterThanEqual":
				return (num1 >= num2);
			case "LessThan":
				return (num1 < num2);
			case "LessThanEqual":
				return (num1 <= num2);
			default:
				return (num1 == num2);
		}
	},
	compareDate : function(op1,operator,op2){
		re = /-/g;
		op1 = op1.replace(re,'/');
		op2 = op2.replace(re,'/');
		var d1 = new Date(op1);
		var d2 = new Date(op2);
		var diff = Date.parse(d1) - Date.parse(d2);
		switch (operator) {
			case "NotEqual":
				return (dif != 0);
			case "GreaterThan":
				return (diff > 0);
			case "GreaterThanEqual":
				return (diff >= 0);
			case "LessThan":
				return (diff < 0);
			case "LessThanEqual":
				return (diff <= 0);
			default:
				return (diff == 0);
		}
	},
	MustChecked : function(name, min, max){
		var groups = document.getElementsByName(name);
		var hasChecked = 0;
		min = min || 1;
		max = max || groups.length;
		for(var i=groups.length-1;i>=0;i--)
			if(groups[i].checked) hasChecked++;
		return min <= hasChecked && hasChecked <= max;
	},
	DoFilter : function(input, filter){
		return new RegExp("^.+\.(?=EXT)(EXT)$".replace(/EXT/g, filter.split(/\s*,\s*/).join("|")), "gi").test(input);
	},
	IsIdCard : function(number){
		var date, Ai;
		var verify = "10x98765432";
		var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
		var area = ['','','','','','','','','','','','北京','天津','河北','山西','内蒙古','','','','','','辽宁','吉林','黑龙江','','','','','','','','上海','江苏','浙江','安微','福建','江西','山东','','','','河南','湖北','湖南','广东','广西','海南','','','','重庆','四川','贵州','云南','西藏','','','','','','','陕西','甘肃','青海','宁夏','新疆','','','','','','台湾','','','','','','','','','','香港','澳门','','','','','','','','','国外'];
		var re = number.match(/^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[x\d])))$/i);
		if(re == null) return false;
		if(re[1] >= area.length || area[re[1]] == "") return false;
		if(re[2].length == 12){
			Ai = number.substr(0, 17);
			date = [re[9], re[10], re[11]].join("-");
		}
		else{
			Ai = number.substr(0, 6) + "19" + number.substr(6);
			date = ["19" + re[4], re[5], re[6]].join("-");
		}
		if(!this.IsDate(date, "ymd")) return false;
		var sum = 0;
		for(var i = 0;i<=16;i++){
			sum += Ai.charAt(i) * Wi[i];
		}
		Ai +=  verify.charAt(sum%11);
		return (number.length ==15 || number.length == 18 && number == Ai);
	},
	IsDate : function(op, formatString){
		formatString = formatString || "ymd";
		var m, year, month, day;
		switch(formatString){
			case "ymd" :
				m = op.match(new RegExp("^((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})$"));
				if(m == null ) return false;
				day = m[6];
				month = m[5]*1;
				year =  (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
				break;
			case "dmy" :
				m = op.match(new RegExp("^(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))$"));
				if(m == null ) return false;
				day = m[1];
				month = m[3]*1;
				year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
				break;
			default :
				break;
		}
		if(!parseInt(month)) return false;
		month = month==0 ?12:month;
		var date = new Date(year, month-1, day);
		return (typeof(date) == "object" && year == date.getFullYear() && month == (date.getMonth()+1) && day == date.getDate());
		function GetFullYear(y){return ((y<30 ? "20" : "19") + y)|0;}
	},
	$ : function (id){
		var tmp = document.getElementById(id);
		if (tmp){
			return tmp;
		}else{
			alert('[Validator.js] id 为:['+id+']的元素未找到!');
		}
	}
}
function bindingValidatorForm(formName,xmlFile){
	var ie=(typeof window.ActiveXObject!="undefined");
	var xmlDoc;
	if(ie){
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	}else {
		xmlDoc=document.implementation.createDocument("","",null);
	}
		xmlDoc.async=false;
		xmlDoc.load(xmlFile);
	if(ie){
		while(xmlDoc.readyState!=4){
	}
		validatorForm(formName,xmlDoc,ie);
	}else {
		xmlDoc.onload=validatorForm(formName,xmlDoc,ie);
	}
}
function validatorForm(formName,xmlDoc,ie){
	var tmpForm;
	var root = xmlDoc.documentElement;
	var tmpForms;
	try{
		tmpForms=root.getElementsByTagName("form");
	}catch (e){
		alert('[Validator.js] load Validator XML Error!');
		return;
	}
	for(var i=0;i<tmpForms.length;i++){
		var tmpFormName=tmpForms[i].getAttribute("name");
		if(tmpFormName == formName){		
		tmpForm=tmpForms[i];
		break ;
		}
	}
	if(tmpForm){
		var fields=tmpForm.getElementsByTagName("field");
		for(i=0;i<fields.length;i++){
			var fieldId=fields[i].getAttribute("id");
			var field=document.getElementById(fieldId);
			if (field){
				for(var j=0;j<fields[i].childNodes.length;j++){
					var tag=fields[i].childNodes[j];
					field.setAttribute('oldStyle',field.style.backgroundColor);
					if(ie){
						field.setAttribute(tag.nodeName,tag.text);
					}else{
						try{
							field.setAttribute(tag.nodeName,tag.textContent);
						}catch(e){}
					}
				}
			} else {
				alert('页面上没有Name为[ '+fieldId+' ]的字段');
			}
		}
	}
}